﻿using Playnite.SDK.Models;
using Playnite.SDK;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ImportExporter.ImportAttributes
{
    public static class ImportDevelopers
    {
        public static void DoImportDevelopers(IPlayniteAPI PlayniteApi, Game game, List<Company> importedCompanyList)
        {
            List<Company> existedCompanyList = PlayniteApi.Database.Companies.ToList();

            // 在imported中根据Id找Name（这个是一定能找到的）
            List<Company> spcificationExistsCompanyList = importedCompanyList.Where<Company>(item =>
            {
                if (game.DeveloperIds != null)
                {
                    return game.DeveloperIds.Contains(item.Id);
                }
                else
                {
                    return false;
                }
            }).ToList();
            // 在existed中根据Name找Id（这个不一定能找到，imported来的可能是新的）
            if (game.DeveloperIds != null)
            {
                game.DeveloperIds.Clear();
                foreach (Company company in spcificationExistsCompanyList)
                {
                    List<Company> foundList = existedCompanyList.FindAll(p => p.Name.Trim().Equals(company.Name.Trim(), StringComparison.OrdinalIgnoreCase)).ToList();
                    if (foundList.Count > 0)
                    {
                        game.DeveloperIds.Add(foundList[0].Id);
                    }
                    else
                    {
                        PlayniteApi.Database.Companies.Add(company);
                        game.DeveloperIds.Add(company.Id);
                    }
                }
            }
        }
    }
}
